/*
Program: DC-SAR, File conf.c
Copyright (C) 2009 Davy De Coninck

This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/

#include "conf.h"
#include "stringfunc.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int create_config_file(){

	FILE *ofp;
	char *mode = "w";
	char outputFilename[] = "/etc/dc-sar.conf";

	ofp = fopen(outputFilename, "w");

	if (ofp == NULL) {
	  fprintf(stderr, "Can't open file %s!\n",
		  outputFilename);
	  return 0;
	}

	fprintf(ofp, "db-host=127.0.0.1\n");
	fprintf(ofp, "db-name=mydatabase\n");
	fprintf(ofp, "db-user=myuser\n");
	fprintf(ofp, "db-pwd=mypassword\n");

	return -1;
}

int read_config_file(clsconfig *conf){
	FILE *ifp;
	char outputFilename[] = "/etc/dc-sar.conf";
	char line [128]; /* or other suitable maximum line size */
	char compare[128];

	ifp = fopen(outputFilename, "r");

	if (ifp == NULL) {
	  fprintf(stderr, "Can't open file %s!\n",
		  outputFilename);
	  return 0;
	}

	while (fgets(line, sizeof line, ifp) != NULL) /* read a line */
        {      
		strcpy(compare, substr(line,0,7));

		if (strcmp(compare, "db-host") == 0)
		{
			strcpy(conf->dbhost, str_replace("\n","",str_replace("db-host=","",line)));
		}

		if (strcmp(compare, "db-name") == 0)
		{
			strcpy(conf->dbname, str_replace("\n","",str_replace("db-name=","",line)));
		}

		if (strcmp(compare, "db-user") == 0)
		{
			strcpy(conf->dbuser, str_replace("\n","",str_replace("db-user=","",line)));
		}

		if (strcmp(compare, "db-pwd=") == 0)
		{
			strcpy(conf->dbpass, str_replace("\n","",str_replace("db-pwd=","",line)));
		}
	}      

	fclose (ifp);
	printf("====>%s\n",conf->dbhost);
	printf("====>%s\n",conf->dbname);
	printf("====>%s\n",conf->dbuser);

	return -1;
}
